<?php

namespace Modules\Shop\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Shop\Entities\Category;
use Modules\Shop\Http\Requests\CategoryRequest;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
        //获取数据表中所有的数据
        //$category = Category::all();
        $category = Category::getTreeCategory();
        //dd($category);
        return view('shop::category.index',compact('category'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        return view('shop::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        //将post提交的数据写入分类数据库中
        Category::create($request->all());
        //设置闪存并返回首页
        session()->flash('success','设置分类成功！');
        return back();
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('shop::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit($id)
    {
        //获取所有的旧数据
        $category = Category::find($id);
        //获取所有的分类数据
        $categorys = Category::getTreeCategory($category);
        return view('shop::category.edit',compact('category','categorys'));
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(CategoryRequest $request,$id)
    {
        //通过ID找到对应的数据
        $category = Category::find($id);
        $post = $request->all();
        $category['cname'] = $post['cname'];
        $category['pid'] = $post['pid'];
        $category->save();
        //设置闪存信息并返回
        session()->flash('success','分类修改成功！');
        return redirect()->route('category.index');
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
        //删除前判断是否有子类
        $category = Category::find($id);
        if (Category::hasChildCategory($category)){
            //如果为真，代表有子类，不允许删除
            session()->flash('danger','该分类存在子类，禁止删除！');
            return back();
        }
        Category::destroy($id);
        //设置闪存信息并返回
        session()->flash('success','分类删除成功！');
        return back();
    }
}
